package com.myframe.www.net;

import android.text.TextUtils;
import android.util.Base64;


import com.myframe.www.model.remote.bean.LoginBean;

import java.util.Random;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

/**
 * Description:
 * Created by Andy Hong on 11/10/2017.
 */

public class AuthorizationV2 {
    private final String chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private final String METHOD_MAC_ALGORITHM = "HmacSHA256";


    /**
     * 获取随机8个字母
     *
     * @param length
     * @return
     */
    private String getRandomString(int length) {
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            sb.append(chars.charAt(random.nextInt(chars.length())));
        }
        return sb.toString();
    }

    /**
     * 转成骆驼命名法（Camel）
     *
     * @param string
     */
    private String toCamelCase(String string) {
        String[] arr = string.split("-");
        StringBuilder sb = new StringBuilder();
        for (String str : arr) {
            sb.append(str.substring(0, 1).toUpperCase())
                    .append(str.substring(1));
        }
        return sb.toString();
    }


    public String createAuthorization(LoginBean token, String url, String method) {
        if (TextUtils.isEmpty(token.getAccessToken())) {
            return "";
        } else {
            StringBuilder sb = new StringBuilder();
            sb.append("MAC id=\"").append(token.getAccessToken());
            String nonce = String.format("%1$s:%2$s", System.currentTimeMillis(), getRandomString(8));
            sb.append("\",nonce=\"").append(nonce);
            sb.append("\",mac=\"").append(createMac(token.getMacKey(), METHOD_MAC_ALGORITHM, createRequestContent(nonce, method, url)));
            return sb.toString();
        }
    }

    private String createRequestContent(String nonce, String method, String url) {
        String[] urlInfo = url.replaceAll("^(http|https)://", "").split("/", 2);
        return String.format("%s\n%s\n%s\n%s\n", nonce, method.toUpperCase(), "/" + urlInfo[1], urlInfo[0]);
    }

    private String createMac(String macKey, String macAlgorithm, String requestContent) {
        try {
            Mac mac = Mac.getInstance(macAlgorithm);
            byte[] secretByte = macKey.getBytes("UTF-8");
            byte[] dataBytes = requestContent.getBytes("UTF-8");
            SecretKey secret = new SecretKeySpec(secretByte, macAlgorithm.toUpperCase());
            mac.init(secret);
            byte[] doFinal = mac.doFinal(dataBytes);
            return Base64.encodeToString(doFinal, Base64.NO_WRAP);
        } catch (Exception ex) {
            //safe
            return null;
        }
    }
}
